/**
 * VUEshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.vueshop.com.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: soubao-java 2020-07-22 $
 */<template>
  <div>
    <div class="item-title">
      <router-link
        class="back"
        :to="{name:'goods_categories',params:{currentPage:$route.params.currentPage}}"
        title="返回列表"
      >
        <i class="fa fa-arrow-circle-o-left"></i>
      </router-link>
      <div class="subject">
        <h3>商品分类 - 添加修改分类</h3>
        <h5>添加或编辑商品分类</h5>
      </div>
    </div>

    <div
      class="explanation"
      style="color: rgb(85, 85, 85); background-color: rgb(243, 244, 244); width: 98%; height: 100%;"
    >
      <div class="bckopa-tips">
        <div class="title">
          <img src="@/static/images/handd.png" alt />
          <h4 title="提示相关设置操作时应注意的要点">操作提示</h4>
        </div>
        <ul>
          <li>温馨提示：顶级分类（一级大类）设为推荐时才会在首页楼层中显示</li>
          <li>最多只能分类到三级</li>
          <li>佣金比例填写0-99整数</li>
        </ul>
      </div>
      <span title="收起提示" id="explanationZoom" style="display: block;"></span>
    </div>

    <el-form ref="form" :model="form" label-width="200px">
      <el-form-item label="分类名称" required>
        <el-input v-model="form.name" size="mini"></el-input>
        <p class="err-msg" v-if="errResult.name && !form.name">{{errResult.name}}</p>
      </el-form-item>
      <el-form-item label="移动端分类名称" required>
        <el-input v-model="form.mobile_name" size="mini"></el-input>
        <p
          class="err-msg"
          v-if="errResult.mobile_name && !form.mobile_name"
        >{{errResult.mobile_name}}</p>
      </el-form-item>
      <el-form-item label="上级分类">
        <el-cascader
          clearable
          filterable
          placeholder="顶级分类"
          v-model="form.parent_ids"
          @change="initParentCat"
          :options="goods_category_tree"
          :props="{ checkStrictly: true, label: 'name', value: 'id'}"
          size="mini"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="导航显示">
        <el-switch v-model="form.is_show" active-value="1" inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="分类分组">
        <el-select v-model="form.cat_group" placeholder="请选择分类分组">
          <el-option v-for="group in 20" :key="group" :label="group" :value="group" size="mini"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类图片">
        <el-upload
          class="avatar-uploader"
          :action="apiHead + '/mall/upload?type=category'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-image
            v-if="form.image"
            :src="form.image"
            style="width:100px; height:100px; display:block;"
          ></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model="form.sort_order" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="抽成比例(%)">
        <el-input v-model="form.commission" @blur="commissionBlur()" size="mini"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="isLoading">确认提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getGoodsCategoryInfo,
  getGoodsCategoryTree,
  updateGoodsCategory,
  addGoodsCategory
} from "@/utils/api";
export default {
  data() {
    return {
      id: this.$route.params.id,
      flag: this.$route.params.flag,
      form: {
        parent_ids: []
      },
      goods_category_tree: [],
      errResult: {},
      isLoading: false
    };
  },
  created() {
    this.getGoodsCategoryTree();
    if (this.$route.params.id) {
      this.getGoodsCategory();
    } else {
      this.initParentCat(); //初始上级分类等相关数据
    }
  },
  methods: {
    getGoodsCategory() {
      var that = this;
      getGoodsCategoryInfo({ id: this.id }).then(function(res) {
        if (that.flag) {
          //添加下级分类
          that.form.parent_ids = res.parent_ids;
        } else {
          that.form = res;
          that.form.parent_ids = that.form.parent_ids.slice(0, -1);
        }
        that.initParentCat(); //请求上级数据后初始上级分类等相关数据
        that.$forceUpdate();
      });
    },
    getGoodsCategoryTree() {
      var that = this;
      getGoodsCategoryTree({ levels: "1,2" }).then(function(res) {
        that.goods_category_tree = res;
      });
    },
    handleAvatarSuccess(res) {
      this.form.image = res.result;
      this.$forceUpdate();
    },
    beforeAvatarUpload(file) {
      const isPic =
        file.type === "image/gif" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg" ||
        file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isPic) {
        this.$message.error("上传图片只能是 JPG、JPEG、PNG、GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isPic && isLt2M;
    },
    initParentCat() {
      var parent_ids = JSON.parse(JSON.stringify(this.form.parent_ids));
      parent_ids.unshift(0);
      this.form.level = parent_ids.length;
      this.form.parent_id = parent_ids[parent_ids.length - 1];
      if (this.form.id && !this.flag) {
        //编辑时为parent_id_path补上当前分类id
        parent_ids.push(this.form.id);
      }
      this.form.parent_id_path = parent_ids.join("_");
    },
    commissionBlur() {
      if (this.form.commission > 99) {
        this.form.commission = 99;
      }
    },
    onSubmit() {
      this.isLoading = true;
      var that = this;
      if (this.form.id && !this.flag) {
        //编辑
        updateGoodsCategory(that.form).then(function(res) {
          if (res.status == 1) {
            that.$message.success({
              message: "保存成功",
              duration: 1000,
              onClose: function() {
                that.$router.push({ name: "goods_categories" });
              }
            });
          } else if (res.status == -1) {
            that.$message.error("参数错误");
            that.errResult = res.result;
          } else {
            that.$message.error(res.msg);
          }
          that.isLoading = false;
        });
      } else {
        //添加
        addGoodsCategory(that.form).then(function(res) {
          if (res.status == 1) {
            that.$message.success({
              message: "添加成功",
              duration: 1000,
              onClose: function() {
                that.$router.push({ name: "goods_categories" });
              }
            });
          } else if (res.status == -1) {
            that.$message.error("参数错误");
            that.errResult = res.result;
          } else {
            that.$message.error(res.msg);
          }
          that.isLoading = false;
        });
      }
    }
  }
};
</script>

<style scoped>
.avatar-uploader-icon {
  line-height: 100px;
}
>>> .el-input__inner {
  width: 200px;
}
</style>
